package com.android.testListen;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class testListen extends Activity {
	private static final int REQUEST_ENABLE_BT = 1;
	private BluetoothAdapter mAdapter = null;
	private BluetoothServerSocket mmServerSocket = null;
	private static final UUID MY_UUID = UUID
			.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
	private static final String NAME = "testListen";
	private static final String TAG = "testListen";
	private static final boolean D = true;
	private InputStream mmInStream;
	private miThread mT;
	private int estado = 1;

	/** Called when the activity is first created. */
	@Override
	public synchronized void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mAdapter = BluetoothAdapter.getDefaultAdapter();
		mT = new miThread();

		if (!mAdapter.isEnabled()) {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
		} else {
			mT.start();
		}


	}

	public synchronized void onDestroy() {

		if (D)	Log.e(TAG, "onDestroy");
		estado=0;
		 mT.cancel();
//		 mT.interrupt();
//		 mT=null;
		if (D)	Log.e(TAG, "Thread cancel");

		if (D)	Log.e(TAG, "onDestroy - join");
		
		try{
		mT.join();
		if (D)	Log.e(TAG, "join ... hecho");
		}catch(InterruptedException e){
			if (D)	Log.e(TAG, "join - interruptedException");
		}
		mT.destroy();
		if (D)	Log.e(TAG, "onDestroy - end");
	}
////////////////////////////////////////////////////////////////////7
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_principal, menu);
		return true;
	}

	private void ensureDiscoverable() {
		if (D)
			Log.e(TAG, "ensure discoverable");
		if (mAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
			Intent discoverableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(
					BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivity(discoverableIntent);
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.discoverable:
			ensureDiscoverable();
			return true;
		}
		return false;
	}

	public void onActivityResult(int requestCode, int resultCode, Intent i) {
		if (D)
			Log.d(TAG, "onActivityResult ");
		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			if (resultCode == Activity.RESULT_OK) {
				if (D)
					Log.e(TAG, "ENABLE_BT OK");
				mT.start();
			} else {
				if (D)
					Log.e(TAG, "ENABLE_BT OK");
				finish();
			}
			break;

		}
	}
/////////////////////////////////////////////////////////7
	private class miThread extends Thread  {
		BluetoothSocket socket = null;
       public void cancel() {
            if (D) Log.d(TAG, "cancel " + this);
            try {
            	
                mmServerSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of server failed", e);
            }
        }
		@Override
		public void run() {

			if (D)	Log.e(TAG, "Thread_" + "run");
			try {
				mmServerSocket = mAdapter
						.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
				if (D)	Log.e(TAG, "serverSocket");
			} catch (IOException e) {
				Log.e(TAG, "listen() failed", e);
				return;
			}
			try {
				if (D)	Log.e(TAG, "Esperando en accept ...");
				socket = mmServerSocket.accept();

				if (D)	Log.e(TAG, "accept");
			} catch (IOException e) {
//				Log.e(TAG, "accept() failed", e);
				Log.e(TAG, "accept failed");
				return;
			}
			if (D)	Log.e(TAG, " getInputStream");
			try {
				mmInStream = socket.getInputStream();
				if (D)
					Log.e(TAG, "getInputStream - OK");
				// Toast.makeText(getApplicationContext(),
				// "inputStream",Toast.LENGTH_SHORT).show();
			} catch (IOException e) {
				Log.e(TAG, "temp sockets not created", e);
				return;
			}

			int bytes;
			byte[] buffer = new byte[1024];
			while (true) {
				try {
					if (D)	Log.e(TAG, "Vamos a leer ...");
					bytes = mmInStream.read(buffer);
					if (D) Log.e(TAG, "Hemos leido!!!!" + bytes + " "
								+ new Integer(new String(buffer, 0, bytes)));
				} catch (IOException e) {
					Log.e(TAG, "disconnected", e);
					break;
				}
			}
		
		}
	}
}// End main class
